import { defineStore } from "pinia";
import Wsocket from "@/utils/Wsocket.js";

export const useGlobalWs = defineStore({
  id: "globalWs",
  state: () => ({
    userList: [],
    userWsMap: {},
    userMsgMap: {},
  }),
  getters: {},
  actions: {
    setUserWs(user) {
      if (!this.userWsMap[user.id]) {
        this.userWsMap[user.id] = new Wsocket({
          onOpen: () => {
            console.log(user.name, "连接成功！");
            this.userWsMap[user.id].send({ event: user.id, data: { user } });
            this.userWsMap[user.id].on(user.id, (res) => {
              if (res.code === 200) {
                const chatRoom1 = res.data.from.id + "-" + res.data.to.id;
                const chatRoom2 = res.data.to.id + "-" + res.data.from.id;
                let chatRoom = chatRoom1;
                // 两种如果存在则取出
                this.userMsgMap[chatRoom1] && (chatRoom = chatRoom1);
                this.userMsgMap[chatRoom2] && (chatRoom = chatRoom2);
                !this.userMsgMap[chatRoom] && (this.userMsgMap[chatRoom] = []);
                const isExist = this.userMsgMap[chatRoom].findIndex((item) => item.id === res.data.id);
                isExist === -1 && this.userMsgMap[chatRoom].push(res.data);
              }
              if (res.code === 201) {
                this.userList = res.data.userList;
              }
            });
          },
          onClose: (res) => {
            console.log(user.name, "关闭连接！");
            if (res.wasClean) {
              this.userWsMap[user.id].close();
              this.userWsMap[user.id] = null;
            }
          },
        });
      }
    },
    addUser(user) {
      this.userList.push(user);
      this.setUserWs(user);
    },
    removeUser(user) {
      this.userWsMap[user.id].send({ event: user.id, close: true });
    },
    sendMsg(msgObj) {
      if (this.userWsMap[msgObj.from.id]) {
        this.userWsMap[msgObj.from.id].send({ event: msgObj.from.id, data: msgObj });
      }
    },

  },
});
